from django.shortcuts import redirect, render
from UserMgr.models import Server
from django.db.models import Q
from django.core.paginator import Paginator
# Create your views here.

def servernav(request):
    return redirect('/showserver/1')


def showserver(request,pindex):
    res_list = Server.objects.all().order_by('-id')
    paginator = Paginator(res_list, 8)
    if pindex == "":  # django中默认返回空值，所以加以判断，并设置默认值为1
        pindex = 1
    else:  # 如果有返回在值，把返回值转为整数型
        int(pindex) 
    page = paginator.page(pindex)  # 传递当前页的实例对象到前端
    return render(request, 'serverlist2.html', context=locals())

def addone(request):
    if request.method == "POST":
        # 获取用户提交的数据 POST请求中
        hostname1 = request.POST.get('hostname')
        os1 = request.POST.get('os')
        cpu1 = request.POST.get('cpu')
        memory1 = request.POST.get('memory')
        ip1 = request.POST.get('ip')
        server1 = Server(hostname=hostname1,os=os1,cpu=cpu1,memory=memory1,ip=ip1)
        server1.save()
        # temp = {'username': u, 'email': e, "gender": g}
        # USER_LIST.append(temp)
    return redirect('/showserver')

def searchsome(request):
    if request.method == "POST":
        hostname = request.POST.get('hostname')
        ip=request.POST.get('ip')
        if ""==hostname and ""==ip:
            return redirect('/showserver')
        else:
            res_list = Server.objects.all().filter(Q(hostname=hostname)|Q(ip=ip))
            return render(request, 'serverlist.html', context=locals())

def toupdate(request,id):
    res_all=Server.objects.all().filter(id=id)
    res_list=res_all[0]
    return render(request,'updateserver.html',context=locals())

def updatebyid(request,id):
    if request.method == "POST":
        hostname1 = request.POST.get('hostname')
        os1 = request.POST.get('os')
        cpu1 = request.POST.get('cpu')
        memory1 = request.POST.get('memory')
        ip1 = request.POST.get('ip')
        Server.objects.filter(id=id).update(hostname=hostname1,os=os1,cpu=cpu1,memory=memory1,ip=ip1)
    return redirect('/showserver')

def deletebyid(request,id):
    Server.objects.filter(id=id).delete()
    res_list = Server.objects.all()
    return redirect('/showserver')